#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Copyright (c) 2008 Andrew Coleman under the MIT License
# See COPYING at the root directory of this project.
#-------------------------------------------------------------------------------
# Standard Modules
import os
import sys
import optparse
# Project Modules
import db

# Static Settings
OutputMode = "debug" # see list of possible modes in output.py

################################################################################
def UseDefaultSettings():
    # Paths
    Settings = {
        "Paths": {
            "BasePath": BasePath,
            "DatabasePath": DatabasePath,
            },
        "Modes": {
            "OutputMode": "debug",
            "ControlMode": "Single User"
            },
        "Defaults": {
            "DefaultPort": 6667,
            "DefaultNickname": "SlimPyBot",
            "DefaultIdent": "SlimPyBot",
            "DefaultRealname": "SlimPyBot",
            "DefaultQuitMessage": "Visit http://code.google.com/p/slimpybot/ to find out more about this IRC bot!",
            },
        "Control": {
            "Modes": [
                # Single User mode:
                # You set a single nickname of an admin
                # user on whatever server(s) you connect to, that will have total
                # control. Be SURE that that user has absolute control over the use
                # of that nickname on every server that the bot is on, or may be on
                # in the future.
                ("Single User", 1),
                # Registration mode:
                # Any user can register with the bot,
                # though only those with a preset admin user/pass (with the bot)
                # will be able to control the bot, and those which are granted
                # powers by the same person. Users will have to "log in" with the
                # bot before using these powers.
                ("Registration", 2),
                # Open mode:
                # Anyone can use the bot. Be sure you trust
                # everyone that may ever come in contact with the bot.
                ("Open", 3),
                # Closed mode:
                # No one can use the powers, this would probably
                # be most useful if you intend to use the bot for only logging.
                ("Closed", 4)
            ],
            "Settings": {
                "Single User": {
                    "User": "AndrewBC",
                    },
                "Registration": {
                    # Registration mode settings
                    # This random string is used to imprint an admin user, if there has not been one imprinted yet.
                    "Rand": "l@@ou3wt4#@dfh$F^@#Fbr5y$U^GGG00#sgDBW\\te6",
                    "Users": list(),
                    },
                "Open": {
                    },
                "Closed": {
                    },
                }
            },
        "IrcNetworks": {
            "PSIGenix": {
                "Nicknames":[Settings["Defaults"]["DefaultNickname"],],
                "Ident":Settings["Defaults"]["DefaultIdent"],
                "Realname":Settings["Defaults"]["DefaultRealname"],
                "Autojoin":False,
                "KnownHosts":[
                    {
                        "Host":"irc.psigenix.net",
                        "Port":Settings["Defaults"]["DefaultPort"]
                    },
                ],
                "KnownChannels":[],
                "AutojoinChannels":[]
                },
            "Freenode": {
                "Nicknames":[Settings["Defaults"]["DefaultNickname"],],
                "Ident":Settings["Defaults"]["DefaultIdent"],
                "Realname":Settings["Defaults"]["DefaultRealname"],
                "Autojoin":True,
                "KnownHosts":[
                    {
                        "Host":"irc.freenode.net",
                        "Port":Settings["Defaults"]["DefaultPort"]
                    },
                ],
                "KnownChannels":["#slimpybot"],
                "AutojoinChannels":["#slimpybot"]
                },
            "AfterNET": {
                "Nicknames":[Settings["Defaults"]["DefaultNickname"],],
                "Ident":Settings["Defaults"]["DefaultIdent"],
                "Realname":Settings["Defaults"]["DefaultRealname"],
                "Autojoin":True,
                "KnownHosts":[
                    {
                        "Host":"irc.afternet.org",
                        "Port":Settings["Defaults"]["DefaultPort"]
                    },
                ],
                "KnownChannels":["#nop","#eve"],
                "AutojoinChannels":["#nop","#eve"]
                }
            }

    }

    Database.execute("CREATE TABLE Paths(PathName TEXT UNIQUE, Path TEXT)")
    Database.executemany("INSERT INTO Paths(PathName, Path) VALUES(?, ?)", Settings["Paths"])

    Database.execute("CREATE TABLE ModeSettings(Setting TEXT UNIQUE, Value TEXT)")
    Database.executemany("INSERT INTO ModeSettings(Setting, Value) values (?, ?)", Settings["Modes"].items())

    Database.execute("CREATE TABLE DefaultSettings(Setting TEXT UNIQUE, Value TEXT)")
    for key, value in Settings["Defaults"].items():
        Database.execute("INSERT INTO DefaultSettings(Setting, Value) values (?, ?)", (key, value))

    Database.execute("CREATE TABLE ControlModes(Id INTEGER PRIMARY KEY, Name TEXT UNIQUE)")
    Database.execute("CREATE TABLE Users(Id INTEGER PRIMARY KEY, Username TEXT UNIQUE)")
    Database.executemany("INSERT INTO ControlModes(Name, Id) VALUES(?, ?)", Settings["Control"]["Modes"])

    Database.execute("CREATE TABLE ControlSettings(Setting TEXT UNIQUE, Value TEXT, Category TEXT)")
    for ControlCategory, ControlSettings in Settings["Control"]["Settings"].items():
        for ControlSettingName, ControlSettingValue in ControlSettings.items():
            if ControlSettingName == "Users":
                Database.executemany("INSERT INTO Users(Username) VALUES(?)", ControlSettingValue)
            else:
                Database.execute("INSERT INTO ControlSettings(Setting, Value, Category) VALUES(?, ?, ?)", (ControlSettingName, ControlSettingValue, ControlCategory))

    Database.execute("CREATE TABLE IrcNetworks(GroupName TEXT UNIQUE, Ident TEXT, Realname TEXT, Autojoin INTEGER)")
    Database.execute("CREATE TABLE IrcNetworkNicknames(GroupName TEXT, Nickname TEXT)")
    Database.execute("CREATE TABLE IrcNetworkKnownHosts(GroupName TEXT, Host TEXT, Port INTEGER)")
    Database.execute("CREATE TABLE IrcNetworkKnownChannels(GroupName TEXT, Channel TEXT)")
    Database.execute("CREATE TABLE IrcNetworkAutojoinChannels(GroupName TEXT, Channel TEXT)")

    for GroupName, GroupInfo in Settings["IrcNetworks"].items():
        Database.execute("INSERT INTO IrcNetworks(GroupName, Ident, Realname, Autojoin) VALUES(?,?,?,?)", (GroupName, GroupInfo["Ident"], GroupInfo["Realname"], int(GroupInfo["Autojoin"])))
        for Nickname in GroupInfo["Nicknames"]:
            Database.execute("INSERT INTO IrcNetworkNicknames(GroupName, Nickname) VALUES(?, ?)", (GroupName, Nickname))
        for KnownChannel in GroupInfo["KnownChannels"]:
            Database.execute("INSERT INTO IrcNetworkKnownChannels(GroupName, Channel) VALUES(?, ?)", (GroupName, KnownChannel))
        for AutojoinChannel in GroupInfo["AutojoinChannels"]:
            Database.execute("INSERT INTO IrcNetworkAutojoinChannels(GroupName, Channel) VALUES(?, ?)", (GroupName, AutojoinChannel))
        for Host in GroupInfo["KnownHosts"]:
            Database.execute("INSERT INTO IrcNetworkKnownHosts(GroupName, Host, Port) VALUES(?, ?, ?)", (GroupName, Host["Host"], Host["Port"]))

    Database.execute("INSERT INTO DefaultSettings(Setting, Value) values(\"DatabaseIsSetup\", 1)")

def LoadSettings():
    pass

#-------------------------------------------------------------------------------
# Set up the module
#-------------------------------------------------------------------------------
Settings = dict()
# See if we need a default


try:
    db.Handler.execute("SELECT Data FROM DefaultSettings WHERE Name=DatabaseIsSetup")
except sqlite3.OperationalError, e:
    if str(e) == "no such table: DefaultSettings":
        print >> sys.stderr, "warning> Settings Database not found, setting up default database."
        setup_db()
    else:
        exit(1)
CurrentFile = os.path.abspath(__file__)
BasePath = os.path.dirname(CurrentFile)
DatabasePath = os.path.join(BasePath, "settings")
DatabaseFile = os.path.join(DatabasePath, "database")